package cn.edu.sdjzu.xg.eagle.controller;

import cn.edu.sdjzu.xg.eagle.service.SchoolService;
import cn.edu.sdjzu.xg.eagle.entity.School;
import cn.edu.sdjzu.xg.eagle.util.Condition;
import cn.edu.sdjzu.xg.eagle.util.ControllerHelper;
import cn.edu.sdjzu.xg.eagle.util.JSONUtil;
import cn.edu.sdjzu.xg.eagle.util.Pagination;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.List;

public class SchoolController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        JSONObject message_jsonObj = new JSONObject();
        response.setContentType("application/json;charset=UTF-8");
        String req_jsonStr = JSONUtil.getJSON(request);
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
        if (req_jsonObj == null) {
            message_jsonObj.put("message", "未收到请求信息！");
            response.getWriter().println(message_jsonObj);
            return;
        }
        try {
            Pagination pagination = ControllerHelper.getPagination(req_jsonObj);

            // 将 Pagination 转换为 List<Condition>
            List<Condition> conditions = ControllerHelper.convertPaginationToConditions(pagination);

            // 调用 SchoolService 的 findAll 方法
            Collection<School> schools = SchoolService.getInstance().findAll(conditions);

            // 使用 FastJSON 2.x 直接序列化对象，默认已禁用循环引用检测
            String schools_json = JSON.toJSONString(schools);
            message_jsonObj.put("totalNum", pagination.getTotalNum());
            message_jsonObj.put("data", schools_json);
            response.getWriter().println(message_jsonObj);
        } catch (Exception e) {
            message_jsonObj.put("message", "网络异常");
            response.getWriter().println(message_jsonObj);
            e.printStackTrace();
        }
    }
}



